package com.davidk.survey.server;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.davidk.survey.server.constants.Constants;
import com.davidk.survey.server.user.User;
import com.davidk.survey.server.user.UserDAO;

@Controller
@RequestMapping("/login")
public class LoginController {

	@ModelAttribute("user")
	@RequestMapping(value = "/", method = RequestMethod.POST)
	public User login(@RequestBody User user, HttpServletRequest request) throws IOException {

		User dbUser = UserDAO.getByName(user.getName());
		if (dbUser == null) {
			try {
				UserDAO.createUser(user);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			user = dbUser;
		}

		request.getSession(true).setAttribute(Constants.SESSION_USER, user);
		return user;
	}
}
